package repository

import (
	"errors"

	"github.com/lab-online/internal/user/constant"
	"github.com/lab-online/internal/user/entity"
	"github.com/lab-online/internal/user/infra/model"
	"gorm.io/gorm"
)

// GetUserByUsername 获取指定 `username` 的用户
func (r *Repository) GetUserByUsername(username string) (entity.UserEntity, error) {
	query := model.NewUser(model.WithUsername(username))
	err := r.db.Where(query).First(&query).Error

	switch {
	case err == nil:
		return query.ToEntity(), nil
	case errors.Is(err, gorm.ErrRecordNotFound):
		return nil, constant.DBErrUserNotFound
	default:
		return nil, constant.DBErrUnknown
	}
}

// GetUnscopedUserByUsername 获取指定 `username` 的用户，不考虑软删除
func (r *Repository) GetUnscopedUserByUsername(username string) (entity.UserEntity, error) {
	query := model.NewUser(model.WithUsername(username))
	if err := r.db.Unscoped().Where(query).First(&query).Error; err != nil {
		return nil, r.errorHandler(err)
	}

	return query.ToEntity(), nil
}

// GetManyUsersByUsername 获取多个用户, 通过 `username`
func (r *Repository) GetManyUsersByUsername(usernames []string) ([]entity.UserEntity, error) {
	var users []*model.User
	if err := r.db.Find(&users, "username IN ?", usernames).Error; err != nil {
		return nil, constant.DBErrUnknown
	} else {
		userEntities := make([]entity.UserEntity, len(users))
		for i, user := range users {
			userEntities[i] = user.ToEntity()
		}
		return userEntities, nil
	}
}

// GetUsers 获取指定Username、Name、Role的所有用户
func (r *Repository) GetUsers(userEntity entity.UserEntity) ([]entity.UserEntity, error) {
	db := r.db.
		Where("username LIKE ?", "%"+userEntity.GetUsername()+"%").
		Where("name LIKE ?", "%"+userEntity.GetName()+"%")
	if userEntity.GetRole() != 0 {
		db = db.Where("role & ? != 0", userEntity.GetRole())
	}

	var users []model.User
	if err := db.Find(&users).Error; err != nil {
		return nil, constant.DBErrUnknown
	} else {
		userEntities := make([]entity.UserEntity, len(users))
		for i, user := range users {
			userEntities[i] = user.ToEntity()
		}
		return userEntities, nil
	}
}
